/**
 * Created by xiongisxiong on 2018/5/18 edited on 5/21
 * 详情界面-歌单列表
 */
import React, { PureComponent } from 'react'
import { View, Text, Image, StyleSheet, TouchableOpacity, FlatList, SectionList } from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import { NavigationActions } from 'react-navigation'

import { screen, color } from '../utils';
import { TextTool, Avatar, IconWidget } from '../widgets'
import { PLAYLIST_DETAIL, TOP_LIST } from '../api'

import { connect } from 'react-redux'
import { setPlayId } from '../redux/actions'

const { H3, Tip, Normal } = TextTool;

class DetailScene extends PureComponent {
  static navigationOptions = ({navigation}) => ({
    header: null,
    // headerTitle: '歌单',
    // headerStyle: {
    //   position: 'absolute',
    //   height: 50,
    //   backgroundColor: 'rgba(0,0,0,0.64)',
    //   zIndex: 100,
    //   top: 0,
    //   left: 0,
    //   right: 0
    // }
  });
  state = {
    dataList: [
      // {title: '致即将逝去的青春',subTitle: '茶几场 - 暖行'},
      // {title: 'zhi致终将逝去的青春', subTitle: 'cha茶几场 - 暖心'}
    ],
    refreshing: true,
    paused: false,
    data: {creator: {}, tracks: []},
  };
  componentWillMount() {
  };
  componentDidMount() {
    this.requestDetail()
  };
  requestDetail = () => {
    try {
      (
        async () => {
          const {id, type = 'playlist' } = this.props.navigation.state.params;
          const url = type === 'playlist' && PLAYLIST_DETAIL || type === 'top' && TOP_LIST; // 歌单 或 排行榜
          const res = await fetch(url + id);
          const { playlist, result } = await res.json();
          const json = playlist || result;
          console.log("Detail页面接口返回的值(json = playlist || result)：", json)
          this.setState({
            dataList: json.tracks.map(item => ({
              ...item,
              title: item.name + ((item.alia && item.alia.length > 0) ? `(${item.alia})` : ''),
              subTitle: (item.ar || item.artists).map(a =>a.name).join('、') + ' - ' + (item.al || item.album).name
            })),
            refreshing: false,
            data: json
          })
        }
      )()
    } catch (err) {alert(err)}    
  };
  // 返回
  goBack = () => {
    const backAction = NavigationActions.back({key: 'Tab'});
    console.log('DetailScenejs文件goBack函数输出', backAction)
    this.props.navigation.dispatch(backAction);
  };
  // 播放歌曲
  playSong = id => {
    const { dispatch, navigation } = this.props;
    console.log('DetailScenejs检测this.props：', this.props)
    dispatch(setPlayId(id));
    navigation.navigate('Player', {title: '播放器'})
  };
  scrollToLocation = (params) => { // 将可视区域定位于特定位置
    console.log('params',params)
  };
  // 跳到UserDetail
  toUserPage = id => {
    this.props.navigation.navigate('UserDetail', {id})
  };
  // 渲染头部
  renderHeader = () => {
    const { data } = this.state;
    return (
      <View style={styles.header}>
        {/* 图片定位为背景 */}
        <Image source={{uri: data && `${data.coverImgUrl}?param=250y250`}} resizeMode='cover' style={[styles.bg, {top:-50, height: screen.width * 0.6 + 50}]} blurRadius={4}/>

        <View style={{flex: 1, flexDirection: 'row', alignItems: 'center', paddingLeft: 10, backgroundColor: 'transparent'}}>
            <View style={{width: screen.width * 0.3, height: screen.width * 0.3}}>
                <Image source={{uri: data && `${data.coverImgUrl}?param=250y250`}} style={{width: '100%', height: '100%'}}/>
            </View>
            <View style={{flex: 1, marginLeft: 15, height: '80%'}}>
                <H3 style={{paddingTop: 15, paddingBottom: 10}} color={color.white}>{data.name}</H3>
                <TouchableOpacity style={{flexDirection: 'row'}} onPress={() => this.toUserPage(data.creator.userId)}>
                    <Avatar img={{uri: `${data.creator.avatarUrl}?param=80y80`}} size={30}/>
                    <Normal style={{paddingVertical: 10, paddingHorizontal: 10}} color={color.white}>{data.creator.nickname}</Normal>
                </TouchableOpacity>
            </View>
        </View>

        {/* 底部四个一列的弹性盒子 */}
        <View style={{height: 50, justifyContent: 'space-around', flexDirection: 'row', backgroundColor: 'transparent', paddingTop: 10, alignItems: 'center'}}>
            <IconWidget icon='ios-star-outline' color={color.white} title={data.subscribedCount}/>
            <IconWidget icon='ios-chatboxes-outline' color={color.white} title={data.commentCount}/>
            <IconWidget icon='ios-open-outline' color={color.white} title={data.shareCount}/>
            <IconWidget icon='ios-download-outline' color={color.white} title={data.white || '下载'}/>
            {/* <View style={{alignItems: 'center'}}>
                <Icon name="ios-star-outline" size={25} color={color.white} />
                <Tip color={color.white}>{data.subscribedCount}</Tip>
            </View> */}
        </View>
      </View>
    )
  };
  // SectionList中每一个部分的头部
  sectionHeader = () => (
    <View style={{height: 50, width: screen.width, flexDirection: 'row', paddingLeft: 10, alignItems: 'center', backgroundColor: '#fff'}}>
        <View style={{width: 25, alignItems: 'center', justifyContent: 'center'}}>
            <TouchableOpacity onPress={this.pause}>
              <Icon name='ios-play-outline' size={30}/>
            </TouchableOpacity>
        </View>
        <View style={{flex: 1, flexDirection: 'row', alignItems: 'center', height: '100%', marginLeft: 10,paddingRight: 10,borderBottomWidth: screen.onePixel, borderColor: color.border}}>
            <H3>{'播放全部'}</H3>
            <Normal>{`（共${this.state.data.tracks.length}首）`}</Normal>
            <View style={{flex: 1}}></View>
            <Icon name='ios-list-outline' size={30} />
        </View>
    </View>
  );
  // 主列表的内容
  renderItem = ({item, index}) => {
    const { currentPlayId } = this.props;
    const flag = currentPlayId === item.id;
    return (
      <View style={{height: 50, width: screen.width, flexDirection: 'row', paddingLeft: 10, alignItems: 'center'}}>
          <View style={{width: 25,justifyContent: 'center',alignItems: 'center'}}>
              {
                flag ? <Icon name='ios-volume-down-outline' color={color.theme} size={22}/> : <Tip title={index + 1} style={{fontSize: 12}}/>
              }
          </View>
          <View style={{flex: 1, flexDirection: 'row', alignItems: 'center', height: '100%', marginLeft: 10, paddingRight: 10, borderBottomWidth: screen.onePixel, borderColor: color.border}}>
              <View style={{flex: 1}}>
                <TouchableOpacity onPress={() => this.playSong(item.id)}>
                  <Normal numberOfLine={1} style={{fontSize: 14}} color={flag ? color.theme : color.black} title={item.title}/>
                  <Tip title={item.subTitle} color={flag ? color.theme : color.black} numberOfLine={1}/>
                </TouchableOpacity>
              </View>
              <View style={{width: 60, flexDirection: 'row', justifyContent: 'flex-end'}}>
                  <Icon name='ios-list-outline' size={30}/>
              </View>
          </View>
      </View>
    )
  };
  scrollToIndex = (params) => { // flatlist滚动到顶部
    alert(JSON.stringjfy(params))
  }
  render() {
    const { dataList, refreshing, data } = this.state;
    return (
      <View>
        <SectionList 
            style={{backgroundColor: '#fff'}}
            onRefresh={this.requestDetail}
            refreshing={refreshing}
            keyExtractor={(item, index) => index}
            sections={[{key: '1',data: dataList}]}
            renderItem={this.renderItem}
            renderSectionHeader={this.sectionHeader}
            ListHeaderComponent={this.renderHeader}
            ListFooterComponent={() => <Text style={{textAlign: 'center', padding: 10, transform: [{scale: 0.857143}]}}>已加载完全部数据</Text>}
            stickySectionHeadersEnabled 
            //往上滑的时候sectionHeader会粘连到顶端
            scrollToLocation={this.scrollToLocation}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  header: {
      height: screen.width * 0.6,
      width: screen.width,
      backgroundColor: '#777777',
      // top: -50,
      // paddingTop: 15,
  },
  bg: {
      position: 'absolute',
      top: 0,
      // bottom: 0,
      // right: 0,
      // left: 0,
      opacity: 0.3,
      height: screen.width * 0.6,
      width: screen.width,
  },
});

// export default DetailScene

// 将reducer返回的新state绑定到属性上this.props,即dispatch也绑定到了this.props上，所以第79行就可以获取到dispatch属性
// mapStateToProps是一个函数，{currentPlay} 为reducer中定义好了的currentPlay
const mapStateToProps = ({currentPlay}) => ({
  currentPlayId: currentPlay.id
});
export default connect(mapStateToProps)(DetailScene);